using UnityEngine;
using System.Collections;

public class EndGameTrigger : MonoBehaviour {
	
	bool isRunning;
	float overAt = 0;
	float runFor = 15f;
	float spawnEvery = 0.5f;
	float lastSpawn = 0;
	
	public GameObject deadBullet;
	
	// Use this for initialization
	void Start () {
		// ...
	}
	
	// Update is called once per frame
	void Update () {
		if (!isRunning) {
			return;
		}
		
		float now = Time.timeSinceLevelLoad;
		if (overAt > now) {
			// do stuff
			if (lastSpawn + spawnEvery < now){
				for (int i=0; i < 5; i++) {
					Vector3 spot = GenerateObjects.getPlayer().transform.position;
					spot.y += 10;
					
					int flip = Random.Range( 1,1 );
					if(flip < 5) {
						spot.x += Random.Range( 3, 10 );
					}
					else {
						spot.x -= Random.Range( 3, 10 );
					}
					
					GameObject obj = (GameObject) Instantiate( deadBullet, spot, Quaternion.identity );
					obj.GetComponent<DestroyAfter>().killAtTime = now + 3 * spawnEvery;
					lastSpawn = now + spawnEvery;
				}
			}
		}
		else {
			Application.LoadLevel( 0 );
		}
	}
	
	// start it up?
	void OnTriggerEnter (Collider other) {
		if (!isRunning) {
			if (other.gameObject.CompareTag( "Player" )) {
				isRunning = true;
				overAt = Time.timeSinceLevelLoad + runFor;
				lastSpawn = Time.timeSinceLevelLoad;
						
				GenerateObjects.getPlayer().GetComponent<CharacterManager>().floatMessage( "YOU WIN!!!", Color.white );
			}
		}
	}
}
